<template>
    <div class="enhanced-weather-display">
        <!-- 顶部控制栏 -->
        <div class="weather-controls">
            <div class="city-selector">
                <input v-model="searchCity" @keyup.enter="addCity" placeholder="输入城市名称添加对比" class="city-input" />
                <button @click="addCity" class="add-city-btn">添加城市</button>
            </div>
            <div class="refresh-controls">
                <button @click="refreshAllWeather" class="refresh-btn">
                    🔄 刷新天气
                </button>
                <div class="auto-refresh">
                    <label>
                        <input type="checkbox" v-model="autoRefresh" />
                        自动刷新 (5分钟)
                    </label>
                </div>
            </div>
        </div>

        <!-- 多城市天气对比 -->
        <div class="cities-weather" v-if="citiesWeather.length > 0">
            <h3 class="section-title">多城市天气对比</h3>
            <div class="cities-grid">
                <div v-for="cityWeather in citiesWeather" :key="cityWeather.city" class="city-weather-card"
                    :class="{ 'primary': cityWeather.city === primaryCity }">
                    <div class="city-header">
                        <h4 class="city-name">{{ cityWeather.city }}</h4>
                        <button @click="removeCity(cityWeather.city)" class="remove-city-btn">×</button>
                    </div>

                    <div class="city-weather-content" v-if="cityWeather.weatherData && cityWeather.weatherData.current">
                        <div class="current-weather">
                            <div class="weather-icon">{{ getWeatherIcon(cityWeather.weatherData.current.text) }}</div>
                            <div class="temperature">
                                <span class="temp-value">{{ cityWeather.weatherData.current.temp?.toFixed(1) }}</span>
                                <span class="temp-unit">°C</span>
                            </div>
                            <div class="weather-text">{{ cityWeather.weatherData.current.text }}</div>
                        </div>

                        <div class="weather-details">
                            <div class="detail-item">
                                <span class="detail-icon">💧</span>
                                <span class="detail-value">{{ cityWeather.weatherData.current.humidity }}%</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-icon">💨</span>
                                <span class="detail-value">{{ cityWeather.weatherData.current.windSpeed?.toFixed(1)
                                    }}m/s</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-icon">🧭</span>
                                <span class="detail-value">{{ cityWeather.weatherData.current.windDir }}</span>
                            </div>
                        </div>
                    </div>
                    <div v-else class="city-weather-content">
                        <div class="loading-placeholder">
                            <div class="loading-spinner">⏳</div>
                            <div class="loading-text">加载中...</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 天气预警通知 -->
        <div class="weather-alerts" v-if="weatherAlerts.length > 0">
            <h3 class="section-title">天气预警</h3>
            <div class="alerts-container">
                <div v-for="alert in weatherAlerts" :key="alert.id" class="alert-item" :class="alert.level">
                    <div class="alert-icon">{{ getAlertIcon(alert.level) }}</div>
                    <div class="alert-content">
                        <div class="alert-title">{{ alert.title }}</div>
                        <div class="alert-description">{{ alert.description }}</div>
                        <div class="alert-time">{{ formatDateTime(alert.time) }}</div>
                    </div>
                    <button @click="dismissAlert(alert.id)" class="dismiss-btn">×</button>
                </div>
            </div>
        </div>

        <!-- 天气统计图表 -->
        <div class="weather-statistics">
            <h3 class="section-title">天气统计</h3>
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon">🌡️</div>
                    <div class="stat-content">
                        <div class="stat-value">{{ getAverageTemp() }}°C</div>
                        <div class="stat-label">平均温度</div>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon">💧</div>
                    <div class="stat-content">
                        <div class="stat-value">{{ getAverageHumidity() }}%</div>
                        <div class="stat-label">平均湿度</div>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon">💨</div>
                    <div class="stat-content">
                        <div class="stat-value">{{ getAverageWindSpeed() }}m/s</div>
                        <div class="stat-label">平均风速</div>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon">☔</div>
                    <div class="stat-content">
                        <div class="stat-value">{{ getRainyDays() }}天</div>
                        <div class="stat-label">雨天数量</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 生活建议 -->
        <div class="life-advice">
            <h3 class="section-title">生活建议</h3>
            <div class="advice-grid">
                <div class="advice-card">
                    <div class="advice-icon">👕</div>
                    <div class="advice-content">
                        <h4>穿衣建议</h4>
                        <p>{{ getClothingAdvice() }}</p>
                    </div>
                </div>

                <div class="advice-card">
                    <div class="advice-icon">🏃</div>
                    <div class="advice-content">
                        <h4>运动建议</h4>
                        <p>{{ getExerciseAdvice() }}</p>
                    </div>
                </div>

                <div class="advice-card">
                    <div class="advice-icon">🚗</div>
                    <div class="advice-content">
                        <h4>出行建议</h4>
                        <p>{{ getTravelAdvice() }}</p>
                    </div>
                </div>

                <div class="advice-card">
                    <div class="advice-icon">🏠</div>
                    <div class="advice-content">
                        <h4>居家建议</h4>
                        <p>{{ getHomeAdvice() }}</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import type { WeatherData } from '@/services/weatherService'
import WeatherService from '@/services/weatherService'

interface WeatherAlert {
    id: string
    level: 'info' | 'warning' | 'danger'
    title: string
    description: string
    time: Date
}

interface CityWeather {
    city: string
    weatherData: WeatherData
}

const searchCity = ref('')
const citiesWeather = ref<CityWeather[]>([])
const primaryCity = ref('北京')
const autoRefresh = ref(false)
const weatherAlerts = ref<WeatherAlert[]>([])

let refreshInterval: number | null = null

// 初始化
onMounted(() => {
    initializeWeather()
    startAutoRefresh()
})

onUnmounted(() => {
    stopAutoRefresh()
})

// 监听自动刷新
watch(autoRefresh, (newVal) => {
    if (newVal) {
        startAutoRefresh()
    } else {
        stopAutoRefresh()
    }
})

// 初始化天气数据
const initializeWeather = async () => {
    // 添加默认城市
    await addCityWeather('北京')
    await addCityWeather('上海')
    await addCityWeather('广州')

    // 生成模拟预警
    generateWeatherAlerts()
}

// 添加城市
const addCity = async () => {
    if (searchCity.value.trim()) {
        await addCityWeather(searchCity.value.trim())
        searchCity.value = ''
    }
}

// 添加城市天气
const addCityWeather = async (city: string) => {
    try {
        console.log(`正在获取城市 ${city} 的天气数据...`)
        // 调用后端API获取天气数据
        const enhancedWeather = await WeatherService.getEnhancedWeather(city)
        console.log(`成功获取 ${city} 的天气数据:`, enhancedWeather)

        console.log(`城市 ${city} 的增强版天气数据:`, enhancedWeather)

        citiesWeather.value.push({
            city,
            weatherData: enhancedWeather.basicWeather || enhancedWeather.BasicWeather
        })

        if (citiesWeather.value.length === 1) {
            primaryCity.value = city
        }
    } catch (error) {
        console.error(`获取城市 ${city} 天气失败:`, error)
        console.log(`为城市 ${city} 创建模拟数据...`)

        // 如果API调用失败，使用模拟数据
        const mockWeatherData: WeatherData = {
            city,
            current: {
                temp: 20 + Math.random() * 20,
                text: getRandomWeatherText(),
                humidity: 40 + Math.random() * 40,
                windSpeed: 2 + Math.random() * 8,
                windDir: getRandomWindDir(),
                pressure: 1000 + Math.random() * 50,
                vis: 5 + Math.random() * 15
            },
            forecast: generateMockForecast(),
            lastUpdated: new Date().toISOString()
        }

        console.log(`城市 ${city} 的模拟数据:`, mockWeatherData)

        citiesWeather.value.push({
            city,
            weatherData: mockWeatherData
        })

        if (citiesWeather.value.length === 1) {
            primaryCity.value = city
        }

        console.log(`当前城市列表:`, citiesWeather.value)
    }
}

// 移除城市
const removeCity = (city: string) => {
    citiesWeather.value = citiesWeather.value.filter(cw => cw.city !== city)
    if (primaryCity.value === city && citiesWeather.value.length > 0) {
        primaryCity.value = citiesWeather.value[0].city
    }
}

// 刷新所有天气
const refreshAllWeather = async () => {
    for (const cityWeather of citiesWeather.value) {
        await addCityWeather(cityWeather.city)
    }
}

// 自动刷新
const startAutoRefresh = () => {
    if (refreshInterval) {
        clearInterval(refreshInterval)
    }

    if (autoRefresh.value) {
        refreshInterval = setInterval(() => {
            refreshAllWeather()
        }, 5 * 60 * 1000) // 5分钟
    }
}

const stopAutoRefresh = () => {
    if (refreshInterval) {
        clearInterval(refreshInterval)
        refreshInterval = null
    }
}

// 生成模拟预报数据
const generateMockForecast = () => {
    const forecast = []
    for (let i = 0; i < 7; i++) {
        const date = new Date()
        date.setDate(date.getDate() + i)

        forecast.push({
            date: date.toISOString(),
            text: getRandomWeatherText(),
            maxTemp: 20 + Math.random() * 15,
            minTemp: 10 + Math.random() * 10,
            windDir: getRandomWindDir(),
            windSpeed: 2 + Math.random() * 8,
            humidity: 40 + Math.random() * 40,
            precip: Math.floor(Math.random() * 100)
        })
    }
    return forecast
}

// 生成天气预警
const generateWeatherAlerts = () => {
    weatherAlerts.value = [
        {
            id: '1',
            level: 'warning',
            title: '大风预警',
            description: '预计未来6小时内将出现6-8级大风，请注意防范',
            time: new Date()
        },
        {
            id: '2',
            level: 'info',
            title: '降水提醒',
            description: '今日有阵雨，出门请携带雨具',
            time: new Date()
        }
    ]
}

// 关闭预警
const dismissAlert = (id: string) => {
    weatherAlerts.value = weatherAlerts.value.filter(alert => alert.id !== id)
}

// 获取天气图标
const getWeatherIcon = (weatherText: string | undefined) => {
    if (!weatherText) return '🌤️'

    const iconMap: Record<string, string> = {
        '晴天': '☀️',
        '多云': '☁️',
        '阴天': '🌥️',
        '小雨': '🌦️',
        '中雨': '🌧️',
        '大雨': '⛈️',
        '雪': '❄️',
        '雾': '🌫️'
    }

    for (const [key, icon] of Object.entries(iconMap)) {
        if (weatherText.includes(key)) {
            return icon
        }
    }

    return '🌤️'
}

// 获取预警图标
const getAlertIcon = (level: string) => {
    const iconMap = {
        'info': 'ℹ️',
        'warning': '⚠️',
        'danger': '🚨'
    }
    return iconMap[level as keyof typeof iconMap] || 'ℹ️'
}

// 格式化时间
const formatDateTime = (date: Date) => {
    return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    })
}

// 统计函数
const getAverageTemp = () => {
    if (citiesWeather.value.length === 0) return '--'
    const validCities = citiesWeather.value.filter(cw => cw.weatherData && cw.weatherData.current)
    if (validCities.length === 0) return '--'
    const total = validCities.reduce((sum, cw) => {
        const current = cw.weatherData?.current
        return sum + (current?.temp || 0)
    }, 0)
    return (total / validCities.length).toFixed(1)
}

const getAverageHumidity = () => {
    if (citiesWeather.value.length === 0) return '--'
    const validCities = citiesWeather.value.filter(cw => cw.weatherData && cw.weatherData.current)
    if (validCities.length === 0) return '--'
    const total = validCities.reduce((sum, cw) => {
        const current = cw.weatherData?.current
        return sum + (current?.humidity || 0)
    }, 0)
    return Math.round(total / validCities.length)
}

const getAverageWindSpeed = () => {
    if (citiesWeather.value.length === 0) return '--'
    const validCities = citiesWeather.value.filter(cw => cw.weatherData && cw.weatherData.current)
    if (validCities.length === 0) return '--'
    const total = validCities.reduce((sum, cw) => {
        const current = cw.weatherData?.current
        return sum + (current?.windSpeed || 0)
    }, 0)
    return (total / validCities.length).toFixed(1)
}

const getRainyDays = () => {
    let count = 0
    citiesWeather.value.forEach(cw => {
        if (cw.weatherData?.forecast) {
            count += cw.weatherData.forecast.filter(day =>
                day.text && (day.text.includes('雨') || day.text.includes('雪'))
            ).length
        }
    })
    return count
}

// 生活建议
const getClothingAdvice = () => {
    const avgTempStr = getAverageTemp()
    if (avgTempStr === '--') return '暂无数据，建议适当增减衣物'
    const avgTemp = parseFloat(avgTempStr)
    if (avgTemp >= 25) return '天气炎热，建议着短袖、短裙等清凉衣物'
    if (avgTemp >= 20) return '天气温暖，建议着长袖衬衫、单裤等服装'
    if (avgTemp >= 15) return '天气凉爽，建议着薄外套、长裤等服装'
    if (avgTemp >= 10) return '天气较冷，建议着厚外套、毛衣等服装'
    return '天气寒冷，建议着棉衣、羽绒服等保暖衣物'
}

const getExerciseAdvice = () => {
    const avgTempStr = getAverageTemp()
    if (avgTempStr === '--') return '暂无数据，建议适当运动'
    const avgTemp = typeof avgTempStr === 'string' ? parseFloat(avgTempStr) : avgTempStr
    if (isNaN(avgTemp)) return '暂无数据，建议适当运动'
    if (avgTemp >= 30 || avgTemp <= 0) return '不建议户外运动，可在室内进行适当运动'
    if (avgTemp >= 20 && avgTemp <= 25) return '天气适宜，非常适合户外运动'
    return '天气较适宜，建议适当运动，注意保暖'
}

const getTravelAdvice = () => {
    const rainyDays = getRainyDays()
    if (rainyDays > 3) return '近期降水较多，出行请携带雨具，注意交通安全'
    if (rainyDays > 0) return '有降水天气，出行请关注天气变化'
    return '天气晴好，适合出行，注意防晒'
}

const getHomeAdvice = () => {
    const avgHumidity = getAverageHumidity()
    if (avgHumidity === '--') return '暂无数据，建议保持室内通风'
    const humidity = typeof avgHumidity === 'string' ? parseFloat(avgHumidity) : avgHumidity
    if (isNaN(humidity)) return '暂无数据，建议保持室内通风'
    if (humidity > 80) return '湿度较大，注意防潮，可适当使用除湿设备'
    if (humidity < 30) return '湿度较低，注意保湿，可适当使用加湿设备'
    return '湿度适宜，室内环境舒适'
}

// 工具函数
const getRandomWeatherText = () => {
    const weathers = ['晴天', '多云', '阴天', '小雨', '中雨', '大雨', '小雪', '中雪', '大雪']
    return weathers[Math.floor(Math.random() * weathers.length)]
}

const getRandomWindDir = () => {
    const directions = ['北风', '东北风', '东风', '东南风', '南风', '西南风', '西风', '西北风']
    return directions[Math.floor(Math.random() * directions.length)]
}
</script>

<style scoped>
.enhanced-weather-display {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.weather-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 15px;
    color: white;
}

.city-selector {
    display: flex;
    gap: 10px;
}

.city-input {
    padding: 10px 15px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    min-width: 200px;
}

.add-city-btn {
    padding: 10px 20px;
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 8px;
    color: white;
    cursor: pointer;
    transition: all 0.3s ease;
}

.add-city-btn:hover {
    background: rgba(255, 255, 255, 0.3);
}

.refresh-controls {
    display: flex;
    align-items: center;
    gap: 20px;
}

.refresh-btn {
    padding: 10px 20px;
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 8px;
    color: white;
    cursor: pointer;
    transition: all 0.3s ease;
}

.refresh-btn:hover {
    background: rgba(255, 255, 255, 0.3);
}

.auto-refresh {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
}

.section-title {
    font-size: 1.5rem;
    margin-bottom: 20px;
    color: #333;
    text-align: center;
}

/* 多城市天气对比 */
.cities-weather {
    margin-bottom: 40px;
}

.cities-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
}

.city-weather-card {
    background: white;
    border-radius: 15px;
    padding: 20px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    border: 2px solid transparent;
}

.city-weather-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}

.city-weather-card.primary {
    border-color: #007bff;
    box-shadow: 0 5px 20px rgba(0, 123, 255, 0.3);
}

.city-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.city-name {
    margin: 0;
    color: #333;
    font-size: 1.2rem;
}

.remove-city-btn {
    background: none;
    border: none;
    font-size: 1.5rem;
    color: #dc3545;
    cursor: pointer;
    padding: 0;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.city-weather-content {
    text-align: center;
}

.current-weather {
    margin-bottom: 20px;
}

.weather-icon {
    font-size: 3rem;
    margin-bottom: 10px;
}

.temperature {
    margin-bottom: 10px;
}

.temp-value {
    font-size: 2rem;
    font-weight: 700;
    color: #333;
}

.temp-unit {
    font-size: 1.2rem;
    color: #666;
}

.weather-text {
    font-size: 1rem;
    color: #666;
    margin-bottom: 15px;
}

.weather-details {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
}

.detail-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 5px;
}

.detail-icon {
    font-size: 1.2rem;
}

.detail-value {
    font-size: 0.9rem;
    color: #333;
    font-weight: 500;
}

/* 天气预警 */
.weather-alerts {
    margin-bottom: 40px;
}

.alerts-container {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.alert-item {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 20px;
    border-radius: 10px;
    background: white;
    box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.alert-item:hover {
    transform: translateX(5px);
}

.alert-item.info {
    border-left: 4px solid #17a2b8;
}

.alert-item.warning {
    border-left: 4px solid #ffc107;
}

.alert-item.danger {
    border-left: 4px solid #dc3545;
}

.alert-icon {
    font-size: 2rem;
}

.alert-content {
    flex: 1;
}

.alert-title {
    font-size: 1.1rem;
    font-weight: 600;
    color: #333;
    margin-bottom: 5px;
}

.alert-description {
    color: #666;
    margin-bottom: 5px;
}

.alert-time {
    font-size: 0.8rem;
    color: #999;
}

.dismiss-btn {
    background: none;
    border: none;
    font-size: 1.5rem;
    color: #999;
    cursor: pointer;
    padding: 0;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 天气统计 */
.weather-statistics {
    margin-bottom: 40px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
}

.stat-card {
    background: white;
    border-radius: 15px;
    padding: 25px;
    text-align: center;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}

.stat-icon {
    font-size: 3rem;
    margin-bottom: 15px;
}

.stat-value {
    font-size: 2rem;
    font-weight: 700;
    color: #333;
    margin-bottom: 10px;
}

.stat-label {
    color: #666;
    font-size: 1rem;
}

/* 生活建议 */
.life-advice {
    margin-bottom: 40px;
}

.advice-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}

.advice-card {
    background: white;
    border-radius: 15px;
    padding: 25px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    display: flex;
    align-items: flex-start;
    gap: 15px;
}

.advice-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}

.advice-icon {
    font-size: 2.5rem;
    flex-shrink: 0;
}

.advice-content h4 {
    margin: 0 0 10px 0;
    color: #333;
    font-size: 1.1rem;
}

.advice-content p {
    margin: 0;
    color: #666;
    line-height: 1.5;
}

/* 加载占位符样式 */
.loading-placeholder {
    text-align: center;
    padding: 40px 20px;
    color: #666;
}

.loading-spinner {
    font-size: 2rem;
    margin-bottom: 15px;
    animation: spin 2s linear infinite;
}

.loading-text {
    font-size: 1rem;
    color: #999;
}

@keyframes spin {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .enhanced-weather-display {
        padding: 15px;
    }

    .weather-controls {
        flex-direction: column;
        gap: 20px;
        text-align: center;
    }

    .city-selector {
        flex-direction: column;
        width: 100%;
    }

    .city-input {
        min-width: auto;
        width: 100%;
    }

    .cities-grid {
        grid-template-columns: 1fr;
    }

    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }

    .advice-grid {
        grid-template-columns: 1fr;
    }
}
</style>